import React, { useState, useEffect } from 'react';
import {
    Card,
    Table,
    Button,
    Space,
    Modal,
    Form,
    Input,
    Select,
    message,
    Tooltip,
    Tag
} from 'antd';
import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    EyeOutlined,
    ExclamationCircleOutlined,
    CheckCircleOutlined,
    CloseCircleOutlined
} from '@ant-design/icons';
import './Device.css';

const { Option } = Select;
const { confirm } = Modal;

interface Device {
    id: string;
    name: string;
    type: string;
    status: 'online' | 'offline' | 'error';
    ip: string;
    location: string;
    createdAt: string;
}

const DeviceManagement: React.FC = () => {
    const [loading, setLoading] = useState<boolean>(false);
    const [devices, setDevices] = useState<Device[]>([]);
    const [modalVisible, setModalVisible] = useState<boolean>(false);
    const [modalTitle, setModalTitle] = useState<string>('添加设备');
    const [form] = Form.useForm();
    const [editingId, setEditingId] = useState<string | null>(null);

    // 模拟获取设备列表
    useEffect(() => {
        fetchDevices();
    }, []);

    const fetchDevices = () => {
        setLoading(true);
        // 模拟API请求
        setTimeout(() => {
            const mockDevices: Device[] = [
                {
                    id: '1',
                    name: '摄像头A',
                    type: 'camera',
                    status: 'online',
                    ip: '192.168.1.100',
                    location: '一号楼北门',
                    createdAt: '2023-05-20 10:30:00'
                },
                {
                    id: '2',
                    name: '摄像头B',
                    type: 'camera',
                    status: 'offline',
                    ip: '192.168.1.101',
                    location: '一号楼南门',
                    createdAt: '2023-05-20 10:35:00'
                },
                {
                    id: '3',
                    name: '传感器A',
                    type: 'sensor',
                    status: 'online',
                    ip: '192.168.1.102',
                    location: '二号楼东侧',
                    createdAt: '2023-05-20 11:00:00'
                },
                {
                    id: '4',
                    name: '传感器B',
                    type: 'sensor',
                    status: 'error',
                    ip: '192.168.1.103',
                    location: '二号楼西侧',
                    createdAt: '2023-05-20 11:05:00'
                },
                {
                    id: '5',
                    name: '控制器A',
                    type: 'controller',
                    status: 'online',
                    ip: '192.168.1.104',
                    location: '三号楼中控室',
                    createdAt: '2023-05-20 11:30:00'
                }
            ];
            setDevices(mockDevices);
            setLoading(false);
        }, 1000);
    };

    // 打开添加设备模态框
    const showAddModal = () => {
        setModalTitle('添加设备');
        setEditingId(null);
        form.resetFields();
        setModalVisible(true);
    };

    // 打开编辑设备模态框
    const showEditModal = (device: Device) => {
        setModalTitle('编辑设备');
        setEditingId(device.id);
        form.setFieldsValue({
            name: device.name,
            type: device.type,
            ip: device.ip,
            location: device.location
        });
        setModalVisible(true);
    };

    // 处理模态框取消
    const handleCancel = () => {
        setModalVisible(false);
    };

    // 处理设备表单提交
    const handleSubmit = () => {
        form.validateFields()
            .then(values => {
                if (editingId) {
                    // 处理编辑设备
                    const updatedDevices = devices.map(device => {
                        if (device.id === editingId) {
                            return { ...device, ...values };
                        }
                        return device;
                    });
                    setDevices(updatedDevices);
                    message.success('设备更新成功！');
                } else {
                    // 处理添加设备
                    const newDevice: Device = {
                        id: String(Date.now()),
                        name: values.name,
                        type: values.type,
                        status: 'offline',
                        ip: values.ip,
                        location: values.location,
                        createdAt: new Date().toLocaleString()
                    };
                    setDevices([...devices, newDevice]);
                    message.success('设备添加成功！');
                }
                setModalVisible(false);
            })
            .catch(info => {
                console.log('Validate Failed:', info);
            });
    };

    // 处理删除设备
    const handleDelete = (id: string) => {
        confirm({
            title: '确定要删除这个设备吗?',
            icon: <ExclamationCircleOutlined />,
            content: '删除后无法恢复，请谨慎操作。',
            onOk() {
                const updatedDevices = devices.filter(device => device.id !== id);
                setDevices(updatedDevices);
                message.success('设备已删除');
            }
        });
    };

    // 查看设备详情
    const viewDeviceDetails = (device: Device) => {
        Modal.info({
            title: `设备详情 - ${device.name}`,
            content: (
                <div>
                    <p><strong>ID:</strong> {device.id}</p>
                    <p><strong>名称:</strong> {device.name}</p>
                    <p><strong>类型:</strong> {
                        device.type === 'camera' ? '摄像头' :
                            device.type === 'sensor' ? '传感器' :
                                device.type === 'controller' ? '控制器' : device.type
                    }</p>
                    <p><strong>状态:</strong> {
                        device.status === 'online' ? '在线' :
                            device.status === 'offline' ? '离线' :
                                device.status === 'error' ? '异常' : device.status
                    }</p>
                    <p><strong>IP地址:</strong> {device.ip}</p>
                    <p><strong>位置:</strong> {device.location}</p>
                    <p><strong>创建时间:</strong> {device.createdAt}</p>
                </div>
            ),
            onOk() { },
        });
    };

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '设备名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            render: (type: string) => {
                let text = '';
                let color = '';

                switch (type) {
                    case 'camera':
                        text = '摄像头';
                        color = 'blue';
                        break;
                    case 'sensor':
                        text = '传感器';
                        color = 'green';
                        break;
                    case 'controller':
                        text = '控制器';
                        color = 'purple';
                        break;
                    default:
                        text = type;
                        color = 'default';
                }

                return <Tag color={color}>{text}</Tag>;
            }
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status: string) => {
                let text = '';
                let color = '';
                let icon = null;

                switch (status) {
                    case 'online':
                        text = '在线';
                        color = 'green';
                        icon = <CheckCircleOutlined />;
                        break;
                    case 'offline':
                        text = '离线';
                        color = 'gray';
                        icon = <CloseCircleOutlined />;
                        break;
                    case 'error':
                        text = '异常';
                        color = 'red';
                        icon = <ExclamationCircleOutlined />;
                        break;
                    default:
                        text = status;
                        color = 'default';
                }

                return (
                    <Tag color={color} icon={icon}>
                        {text}
                    </Tag>
                );
            }
        },
        {
            title: 'IP地址',
            dataIndex: 'ip',
            key: 'ip',
        },
        {
            title: '位置',
            dataIndex: 'location',
            key: 'location',
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
        },
        {
            title: '操作',
            key: 'action',
            render: (_: any, record: Device) => (
                <Space size="middle">
                    <Tooltip title="查看">
                        <Button
                            type="text"
                            icon={<EyeOutlined />}
                            onClick={() => viewDeviceDetails(record)}
                        />
                    </Tooltip>
                    <Tooltip title="编辑">
                        <Button
                            type="text"
                            icon={<EditOutlined />}
                            onClick={() => showEditModal(record)}
                        />
                    </Tooltip>
                    <Tooltip title="删除">
                        <Button
                            type="text"
                            danger
                            icon={<DeleteOutlined />}
                            onClick={() => handleDelete(record.id)}
                        />
                    </Tooltip>
                </Space>
            ),
        },
    ];

    return (
        <div className="device-management">
            <Card
                title="设备管理"
                extra={
                    <Button type="primary" icon={<PlusOutlined />} onClick={showAddModal}>
                        添加设备
                    </Button>
                }
            >
                <Table
                    columns={columns}
                    dataSource={devices}
                    rowKey="id"
                    loading={loading}
                    pagination={{ pageSize: 10 }}
                />
            </Card>

            <Modal
                title={modalTitle}
                open={modalVisible}
                onOk={handleSubmit}
                onCancel={handleCancel}
                destroyOnClose={true}
            >
                <Form
                    form={form}
                    layout="vertical"
                    name="deviceForm"
                >
                    <Form.Item
                        name="name"
                        label="设备名称"
                        rules={[{ required: true, message: '请输入设备名称' }]}
                    >
                        <Input placeholder="请输入设备名称" />
                    </Form.Item>
                    <Form.Item
                        name="type"
                        label="设备类型"
                        rules={[{ required: true, message: '请选择设备类型' }]}
                    >
                        <Select placeholder="请选择设备类型">
                            <Option value="camera">摄像头</Option>
                            <Option value="sensor">传感器</Option>
                            <Option value="controller">控制器</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="ip"
                        label="IP地址"
                        rules={[
                            { required: true, message: '请输入IP地址' },
                            { pattern: /^(\d{1,3}\.){3}\d{1,3}$/, message: '请输入有效的IP地址' }
                        ]}
                    >
                        <Input placeholder="例如: 192.168.1.100" />
                    </Form.Item>
                    <Form.Item
                        name="location"
                        label="设备位置"
                        rules={[{ required: true, message: '请输入设备位置' }]}
                    >
                        <Input placeholder="请输入设备位置" />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default DeviceManagement; 